import re

chapter_pattern = re.compile(r'第[一二三四五六七八九十百千万0-9]+章')
second_chapter_pattern = re.compile(r'第[一二三四五六七八九十百千万0-9]+条')

def split_common(value: str):
    dic = split(value, chapter_pattern)
    res = {}
    for k, v in dic.items():
        if len(v) > 500:
            sdic = split(v, second_chapter_pattern)
            for sk in sdic:
                res[f'{k} {sk}'] = sdic[sk]
        else:
            res[k] = v
    return res

def split(value: str, pattern):
    chapters = pattern.findall(value)
    if not chapters:
        return {"全文": value}
    # 按章节标题分割文本
    split_parts = pattern.split(value)

    # 组合章节标题和内容（忽略空字符串）
    chapter_dict = {}
    for i, chapter_title in enumerate(chapters):
        # 取分割后的对应部分作为章节内容，去除首尾空白
        chapter_content = split_parts[i+1].strip()
        if len(chapter_content) > 10:
            chapter_dict[chapter_title] = chapter_content

    return chapter_dict

def split_file(dir):
    res = []
    with open(file= dir, mode='r', encoding='utf8') as f:
        lines = f.readlines()
        for text in lines:
            text = text.strip()
            if len(text) > 10:
                d = split_common(text)
                for k in d:
                    res.append(f'{k}: {d[k]}')
    return res
if __name__ == '__main__':
    lines = split_file("c:/ai/doc/消费者权益保护法.txt")
    print('\n'.join(lines))
